import React, { Component, createRef } from "react";
import { Form, Input, Button, message } from "antd";
import { UserOutlined, LockOutlined, KeyOutlined } from "@ant-design/icons";

import Captcha from "../../components/Captcha"

import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from "react-router-dom"
class Passwdlogin extends Component {
  constructor(props) {
    super(props);
    this.capRef = createRef();
  }
  render() {
    return (
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{}}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: "请输入您的用户名!",
            },
          ]}
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="Username"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: "请输入您的密码!",
            },
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="Password"
          />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            {
              required: true,
              message: "请输入您的验证码!",
            },
          ]}
        >
          <div>
            <Input
                prefix={<KeyOutlined className="site-form-item-icon" />}
                type="text"
                placeholder="Captcha"
                style={{width:"70%", marginRight:"7px"}}
            />
            <Captcha h={32} w={96} setKey={this.getKey} ref={this.capRef}/>
          </div>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
            block
            style={{borderRadius:"15px"}}
          >
            Log in
          </Button>
        </Form.Item>
      </Form>
    );
  }
  onFinish = (values) => {
    values.key = this.state.key
    req.post(url.PasswdLogin, values).then(res => {
      if(res.data.errNo === 0) {
        message.success("登录成功！", 2, () => {
          this.props.history.push("/dashboard")
        });
      }else {
        message.error(res.data.errText, 2, () => {
          // console.log(this.capRef.current);
          this.capRef.current.loadCaptcha();
        });
      }
    });
  };
  getKey = key => {
      this.setState({
          key
      })
  }
}


export default withRouter(Passwdlogin);
